#include "widget.h"
#include "ui_widget.h"

#include <QDebug>
#include <QtMath>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    connect(ui->horizontalSlider, SIGNAL(valueChanged(int)),
            this, SLOT(do_valueChanged(int)));
    connect(ui->horizontalScrollBar, SIGNAL(valueChanged(int)),
            this, SLOT(do_valueChanged(int)));
    connect(ui->dial, SIGNAL(valueChanged(int)),
            this, SLOT(do_valueChanged(int)));
}

Widget::~Widget()
{
    if (ui) {
        delete ui;
        ui = nullptr;
    }
}

void Widget::do_valueChanged(int value)
{
    ui->progressBar->setValue(value);
    QObject *obj = sender();
    qDebug() << QString("Object Address : %1 = 0x%2").arg(obj->metaObject()->className()).arg(reinterpret_cast<quintptr>(obj), 0, 16);
    if ( reinterpret_cast<quintptr>(obj) == reinterpret_cast<quintptr>(ui->horizontalSlider) ) {
        if ( ui->dial->value() != ui->progressBar->value() ) { ui->dial->setValue(value); }
        if ( ui->horizontalScrollBar->value() != ui->progressBar->value() ) { ui->horizontalScrollBar->setValue(value); }
    } else if ( reinterpret_cast<quintptr>(obj) == reinterpret_cast<quintptr>(ui->horizontalScrollBar) ) {
        if ( ui->dial->value() != ui->progressBar->value() ) { ui->dial->setValue(value); }
        if ( ui->horizontalSlider->value() != ui->progressBar->value() ) { ui->horizontalSlider->setValue(value); }
        ui->dial->setValue(value);
        ui->horizontalSlider->setValue(value);
    } else if ( reinterpret_cast<quintptr>(obj) == reinterpret_cast<quintptr>(ui->dial) ) {
        if ( ui->horizontalSlider->value() != ui->progressBar->value() ) { ui->horizontalSlider->setValue(value); }
        if ( ui->horizontalScrollBar->value() != ui->progressBar->value() ) { ui->horizontalScrollBar->setValue(value); }
    } else {
        qDebug() << QStringLiteral("Error : Unsupported unknown object");
    }
}

void Widget::on_checkBoxInverted_clicked(bool checked)
{
    ui->progressBar->setInvertedAppearance(checked);
}

void Widget::on_checkBoxVisible_clicked(bool checked)
{
    ui->progressBar->setTextVisible(checked);
}

void Widget::on_radioButtonPercent_clicked()
{
    ui->progressBar->setFormat(QStringLiteral("%p%"));
}

void Widget::on_radioButtonValue_clicked()
{
    ui->progressBar->setFormat(QStringLiteral("%v"));
}

